import * as Cesium from "cesium";

// 添加单个模型primitive
let modelObj = {}
export async function createModelPrimitive(options) {
    const { id, url,text, position, scale = 1.0, color, height = 0 } = options;
    try {
        const { pixelSize = 50 } = options;

        // 创建模型矩阵
        const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
            Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.hei || height)
        );
        console.log('url',url)
        // 使用Cesium.Model.fromGltf加载模型
        const model = await Cesium.Model.fromGltf({
            id,
            url,
            modelMatrix: modelMatrix,
            scale: scale,
            maximumScale: 10000,
            minimumPixelSize: 64,
            color: color || Cesium.Color.WHITE,
            silhouetteColor: Cesium.Color.RED,
            silhouetteSize: 10.0,
            heightReference: Cesium.HeightReference.NONE,
            debugShowBoundingVolume: false,
            debugWireframe: false
        });
        // 添加模型到场景
        let models = viewer.scene.primitives.add(model);
        modelObj[id] = models

        // 创建标签（不使用高度参考）
        const labelCollection = viewer.scene.primitives.add( new Cesium.LabelCollection({
            scene: viewer.scene
        }))

        const label = labelCollection.add({
            id:id + '_text',
            position: Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.hei),
            text: text,
            font: '14pt Arial',
            pixelOffset: new Cesium.Cartesian2(0, -pixelSize / 2 - 10),
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            showBackground:true,
            backgroundColor:new Cesium.Color.fromCssColorString("rgba(1,33,22,1)")
            // 移除 heightReference 或者稍后设置
        });
        modelObj[id + '_text'] = label
    } catch (error) {
        console.error('加载模型失败:', error);
        throw error;
    }
}

export async function editModelPrimitive(options) {
    const { id,text,position } = options;
    try {
        if(modelObj[id + '_text']){
            // model[id].text = text
            modelObj[id + '_text'].position = Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.hei)
        }
        if(modelObj[id]){
            // 创建模型矩阵
            const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
                Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.hei || height)
            );
            modelObj[id].modelMatrix = modelMatrix
        }
    } catch (error) {
        console.error('加载模型失败:', error);
        throw error;
    }
}
